import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { useNavigate } from 'react-router-dom'

const API_BASE_URL = 'http://localhost:5000/api'

export default function CirclesPage() {
  const [circles, setCircles] = useState([])
  const [loading, setLoading] = useState(false)
  const [showCreateDialog, setShowCreateDialog] = useState(false)
  const [showJoinDialog, setShowJoinDialog] = useState(false)
  const [newCircleName, setNewCircleName] = useState('')
  const [newCircleDescription, setNewCircleDescription] = useState('')
  const [joinCode, setJoinCode] = useState('')
  const navigate = useNavigate()

  const user = JSON.parse(localStorage.getItem('user') || '{}')

  useEffect(() => {
    loadCircles()
  }, [])

  const loadCircles = async () => {
    setLoading(true)
    try {
      // 模拟数据，实际应该调用API
      setCircles([
        {
          id: 1,
          name: '黄山徒步团',
          description: '一起征服黄山的美景',
          member_count: 8,
          created_at: '2024-01-15'
        },
        {
          id: 2,
          name: '西湖骑行队',
          description: '环西湖骑行，享受美好时光',
          member_count: 12,
          created_at: '2024-01-20'
        }
      ])
    } catch (error) {
      console.error('加载圈子失败:', error)
    } finally {
      setLoading(false)
    }
  }

  const createCircle = async () => {
    if (!newCircleName.trim()) return

    try {
      // 这里应该调用API创建圈子
      const newCircle = {
        id: Date.now(),
        name: newCircleName,
        description: newCircleDescription,
        member_count: 1,
        created_at: new Date().toISOString().split('T')[0]
      }
      setCircles([...circles, newCircle])
      setNewCircleName('')
      setNewCircleDescription('')
      setShowCreateDialog(false)
    } catch (error) {
      console.error('创建圈子失败:', error)
    }
  }

  const joinCircle = async () => {
    if (!joinCode.trim()) return

    try {
      // 这里应该调用API加入圈子
      console.log('加入圈子:', joinCode)
      setJoinCode('')
      setShowJoinDialog(false)
      loadCircles()
    } catch (error) {
      console.error('加入圈子失败:', error)
    }
  }

  const logout = () => {
    localStorage.removeItem('user')
    navigate('/login')
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* 头部 */}
      <div className="bg-white shadow-sm border-b">
        <div className="max-w-md mx-auto px-4 py-4 flex justify-between items-center">
          <div>
            <h1 className="text-xl font-bold walker-green">WalkerRadio</h1>
            <p className="text-sm text-gray-600">欢迎，{user.nickname || user.phone}</p>
          </div>
          <Button variant="outline" size="sm" onClick={logout}>
            退出
          </Button>
        </div>
      </div>

      {/* 主要内容 */}
      <div className="max-w-md mx-auto p-4">
        {/* 操作按钮 */}
        <div className="grid grid-cols-2 gap-4 mb-6">
          <Button 
            onClick={() => setShowCreateDialog(true)}
            className="bg-walker-orange hover:bg-walker-orange/90"
          >
            创建圈子
          </Button>
          <Button 
            variant="outline"
            onClick={() => setShowJoinDialog(true)}
          >
            加入圈子
          </Button>
        </div>

        {/* 圈子列表 */}
        <div className="space-y-4">
          <h2 className="text-lg font-semibold text-gray-800">我的圈子</h2>
          
          {loading ? (
            <div className="text-center py-8 text-gray-500">加载中...</div>
          ) : circles.length === 0 ? (
            <div className="text-center py-8 text-gray-500">
              <p>还没有加入任何圈子</p>
              <p className="text-sm mt-2">创建或加入一个圈子开始你的户外之旅吧！</p>
            </div>
          ) : (
            circles.map(circle => (
              <div 
                key={circle.id}
                className="bg-white rounded-lg p-4 shadow-sm border cursor-pointer hover:shadow-md transition-shadow"
                onClick={() => navigate(`/circle/${circle.id}`)}
              >
                <div className="flex justify-between items-start mb-2">
                  <h3 className="font-semibold text-gray-800">{circle.name}</h3>
                  <span className="text-sm text-gray-500">{circle.member_count}人</span>
                </div>
                <p className="text-gray-600 text-sm mb-2">{circle.description}</p>
                <p className="text-xs text-gray-400">创建于 {circle.created_at}</p>
              </div>
            ))
          )}
        </div>
      </div>

      {/* 创建圈子对话框 */}
      {showCreateDialog && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
          <div className="bg-white rounded-lg p-6 w-full max-w-sm">
            <h3 className="text-lg font-semibold mb-4">创建新圈子</h3>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  圈子名称
                </label>
                <Input
                  placeholder="输入圈子名称"
                  value={newCircleName}
                  onChange={(e) => setNewCircleName(e.target.value)}
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  圈子描述
                </label>
                <Input
                  placeholder="输入圈子描述"
                  value={newCircleDescription}
                  onChange={(e) => setNewCircleDescription(e.target.value)}
                />
              </div>
              <div className="flex space-x-3">
                <Button 
                  onClick={createCircle}
                  className="flex-1 bg-walker-orange hover:bg-walker-orange/90"
                  disabled={!newCircleName.trim()}
                >
                  创建
                </Button>
                <Button 
                  variant="outline"
                  onClick={() => setShowCreateDialog(false)}
                  className="flex-1"
                >
                  取消
                </Button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 加入圈子对话框 */}
      {showJoinDialog && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
          <div className="bg-white rounded-lg p-6 w-full max-w-sm">
            <h3 className="text-lg font-semibold mb-4">加入圈子</h3>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  邀请码
                </label>
                <Input
                  placeholder="输入圈子邀请码"
                  value={joinCode}
                  onChange={(e) => setJoinCode(e.target.value)}
                />
              </div>
              <div className="flex space-x-3">
                <Button 
                  onClick={joinCircle}
                  className="flex-1 bg-walker-orange hover:bg-walker-orange/90"
                  disabled={!joinCode.trim()}
                >
                  加入
                </Button>
                <Button 
                  variant="outline"
                  onClick={() => setShowJoinDialog(false)}
                  className="flex-1"
                >
                  取消
                </Button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

